package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"newapp/model"
	"newapp/tool"
	"strings"
)

func UserMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		//获取authorization header
		tokenString := context.GetHeader("Authorization")

		if tokenString == " "|| !strings.HasPrefix(tokenString, "Bearer"){
			context.JSON(http.StatusUnauthorized, gin.H{
				"code":401,
				"msg":"权限不足1",
			})
			context.Abort()
			return
		}
		tokenString = tokenString[7:]
		token, claims, err := tool.ParseToken(tokenString)
		if err != nil || !token.Valid {
			context.JSON(http.StatusUnauthorized, gin.H{
				"code":401,
				"msg":"权限不足2",
			})
			context.Abort()
			return
		}
		//通过权限验证，获取claims中的userid
		userId := claims.Id
		//userName := claims.UserName
		db := tool.GetDB()
		var user model.User
		db.First(&user, userId)

		if user.ID == 0{
			context.JSON(http.StatusUnauthorized, gin.H{
				"code":401,
				"msg":"权限不足3",
			})
			context.Abort()
			return
		}

		context.Set("user", user)
		context.Next()
	}
}
